<?php

namespace App\Middleware;

use App\Exception\BusinessException;
use App\Service\JWTService;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * 用户 token 校验中间件
 *
 * @author WangBin
 */
class UserTokenMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 获取请求头中的 token
        $token = $request->getHeader('Authorization');
        if(empty($token)) {
            BusinessException::error(403, '拒绝访问');
        }
        $token = str_replace('Bearer ', '', $token);
        $result = JWTService::getInstance()->decode($token);
        if(empty($result)) {
            BusinessException::error(401, '请重新登录');
        }
        $request->withAttribute('user_id', $result['user_id']);
        $request->withAttribute('username', $result['username']);
        $request->withAttribute('nickname', $result['nickname']);

        return $handler->handle($request);
    }
}